package com.party.web.web.controller.gatherInfo;

import com.google.common.base.Strings;
import com.party.api.dto.idcard.request.IdcardVerifyRequest;
import com.party.api.dto.idcard.response.IdcardVerifyResult;
import com.party.api.service.idcard.IIdcardVerifyService;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.utils.StringUtils;
import com.party.core.model.BaseModel;
import com.party.core.model.city.Area;
import com.party.core.model.competition.CompetitionBusiness;
import com.party.core.model.gatherInfo.*;
import com.party.core.model.member.*;
import com.party.core.model.system.SysConfig;
import com.party.core.service.city.IAreaService;
import com.party.core.service.competition.ICompetitionBusinessService;
import com.party.core.service.gatherInfo.IGatherInfoGroupService;
import com.party.core.service.gatherInfo.IGatherInfoItineraryService;
import com.party.core.service.gatherInfo.IGatherInfoMemberService;
import com.party.core.service.gatherInfo.IGatherInfoProjectService;
import com.party.core.service.gatherInfo.biz.GatherInfoMembersBizService;
import com.party.core.service.member.IIndustryService;
import com.party.core.service.member.IMemberInfoService;
import com.party.core.service.member.IMemberService;
import com.party.core.service.member.IPartnerMemberService;
import com.party.core.service.member.biz.MemberPersonalCountBizService;
import com.party.core.service.system.ISysConfigService;
import com.party.web.biz.file.ExcelExportService;
import com.party.web.biz.gatherInfo.ItineraryBizService;
import com.party.web.biz.system.member.MemberBizService;
import com.party.core.utils.MyBeanUtils;
import com.party.web.utils.RealmUtils;
import com.party.web.utils.excel.ExportExcel;
import com.party.web.web.annotation.ControlParam;
import com.party.web.web.annotation.DataControl;
import com.party.web.web.dto.AjaxResult;
import com.party.web.web.dto.input.common.CommonInput;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 人员信息采集表单
 *
 * @author Administrator
 */
@Controller
@RequestMapping("gatherInfo/member")
public class GatherInfoMemberController {
    @Value("#{apishow['apishow.appid']}")
    private String appid;
    @Value("#{apishow['apishow.appSecret']}")
    private String appSecret;

    @Autowired
    private IGatherInfoMemberService gatherInfoMemberService;
    @Autowired
    private IGatherInfoProjectService gatherInfoProjectService;
    @Autowired
    private IGatherInfoGroupService gatherInfoGroupService;
    @Autowired
    private IAreaService areaService;
    @Autowired
    private IIndustryService industryService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private MemberBizService memberBizService;
    @Autowired
    private IMemberInfoService memberInfoService;
    @Autowired
    private GatherInfoMembersBizService gatherInfoMembersBizService;
    @Autowired
    private IGatherInfoItineraryService gatherInfoItineraryService;
    @Autowired
    private ItineraryBizService itineraryBizService;
    @Autowired
    private ExcelExportService excelExportService;
    @Autowired
    private IPartnerMemberService partnerMemberService;
    @Autowired
    private MemberPersonalCountBizService memberPersonalCountBizService;
    @Autowired
    private IIdcardVerifyService iIdcardVerifyService;
    @Autowired
    private ICompetitionBusinessService competitionBusinessService;
    @Autowired
    private ISysConfigService sysConfigService;

    private final String ID_CARD_VERIFY_SWITCH = "IDCardVerifySwitch";

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 列表
     *
     * @param page
     * @return
     * @throws Exception
     */
    @DataControl
    @RequestMapping("list")
    public ModelAndView list(Page page, Member member, String pGroupId, CommonInput commonInput, String projectTitle,
                             @ControlParam(table = "gather_info_project", column = "create_by", getMethodName = "getProjectId") GatherInfoMember memberInfo) throws Exception {
        memberInfo.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        ModelAndView mv = new ModelAndView("gatherInfo/memberList");
        Map<String, Object> params = CommonInput.appendParams(commonInput);

        params.put("fullname", member.getFullname());
        params.put("mobile", member.getMobile());
        params.put("sex", member.getSex());
        params.put("isCertified", member.getIsCertified());

        if (commonInput.getLimit() == null) {
            commonInput.setLimit(100);
        }
        page.setLimit(commonInput.getLimit());

        String groupId = memberInfo.getGroupId();

        if (StringUtils.isNotEmpty(pGroupId)) {
            memberInfo.setGroupId(pGroupId);
        }

        CompetitionBusiness competitionBusiness = competitionBusinessService.findByCompetitionId(memberInfo.getProjectId());
        if (null != competitionBusiness) {
            params.put("businessId", competitionBusiness.getBusinessId());
            mv.addObject("businessId", competitionBusiness.getBusinessId());
        }
        params.put("projectTitle", projectTitle);
        List<Map<String, Object>> memberInfos = gatherInfoMemberService.webListPage(memberInfo, params, page);
        if (StringUtils.isEmpty(groupId)) {
            memberInfo.setGroupId("");
        } else {
            memberInfo.setGroupId(groupId);
        }
        mv.addObject("projectTitle", projectTitle);
        mv.addObject("page", page);
        mv.addObject("memberInfos", memberInfos);
        mv.addObject("memberInfo", memberInfo);
        mv.addObject("input", commonInput);

        String projectId = memberInfo.getProjectId();

        if (StringUtils.isNotEmpty(pGroupId)) {
            GatherInfoGroup gatherInfoGroup = gatherInfoGroupService.get(pGroupId);
            if (null == gatherInfoGroup) {
                return new ModelAndView(Constant.ERROR_402);
            }
            mv.addObject("group", gatherInfoGroup);

            projectId = gatherInfoGroup.getProjectId();
        }

        if (StringUtils.isNotEmpty(projectId)) {
            GatherInfoProject gatherInfoProject = gatherInfoProjectService.get(projectId);
            mv.addObject("project", gatherInfoProject);
        }

        GatherInfoGroup t = new GatherInfoGroup();
        t.setProjectId(projectId);
        List<GatherInfoGroup> groups = gatherInfoGroupService.list(t);
        mv.addObject("groups", groups);

        mv.addObject("pGroupId", pGroupId);
        return mv;
    }

    /**
     * 人员信息导出
     *
     * @param commonInput
     * @param memberInfo
     * @param member
     * @param response
     * @return
     */
    @DataControl
    @ResponseBody
    @RequestMapping(value = "exportMemberInfo", method = RequestMethod.POST)
    public AjaxResult exportMemberInfo(CommonInput commonInput, Member member, String projectTitle,
                                       @ControlParam(table = "gather_info_project", column = "create_by", getMethodName = "getProjectId") GatherInfoMember memberInfo) {
        try {
            GatherInfoProject gatherInfoProject = gatherInfoProjectService.get(memberInfo.getProjectId());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String fileName = gatherInfoProject.getTitle() + "人员信息" + sdf.format(new Date()) + ".xlsx";

            Map<String, Object> params = CommonInput.appendParams(commonInput);
            params.put("fullname", member.getFullname());
            params.put("mobile", member.getMobile());
            params.put("sex", member.getSex());
            CompetitionBusiness competitionBusiness = competitionBusinessService.findByCompetitionId(memberInfo.getProjectId());
            if (null != competitionBusiness) {
                params.put("businessId", competitionBusiness.getBusinessId());
            }
            params.put("projectTitle", projectTitle);
            List<GatherInfoMemberOutput> memberInfos = gatherInfoMemberService.exportList(memberInfo, params);
            for (GatherInfoMemberOutput output : memberInfos) {
                if (StringUtils.isEmpty(output.getGroupName())) {
                    output.setGroupName("未分配");
                }
                if (output.getSex() != null) {
                    output.setSexName(output.getSex() == 1 ? "男" : "女");
                }
                if (output.getGoShuttle() != null) {
                    output.setGoShuttleName(output.getGoShuttle() == 1 ? "是" : "否");
                }
                if (output.getBackShuttle() != null) {
                    output.setBackShuttleName(output.getBackShuttle() == 1 ? "是" : "否");
                }

                if (StringUtils.isNotEmpty(output.getBaseStatus())) {
                    switch (Integer.valueOf(output.getBaseStatus())) {
                        case 1:
                            output.setBaseStatus("待审核");
                            break;
                        case 2:
                            output.setBaseStatus("已通过");
                            break;
                        case 3:
                            output.setBaseStatus("未通过");
                        default:
                            break;
                    }
                }

                if (StringUtils.isNotEmpty(output.getInsuranceStatus())) {
                    switch (Integer.valueOf(output.getInsuranceStatus())) {
                        case 1:
                            output.setInsuranceStatus("待审核");
                            break;
                        case 2:
                            output.setInsuranceStatus("已通过");
                            break;
                        case 3:
                            output.setInsuranceStatus("未通过");
                        default:
                            break;
                    }
                }

                if (StringUtils.isNotEmpty(output.getItineraryStatus())) {
                    switch (Integer.valueOf(output.getItineraryStatus())) {
                        case 1:
                            output.setItineraryStatus("待审核");
                            break;
                        case 2:
                            output.setItineraryStatus("已通过");
                            break;
                        case 3:
                            output.setItineraryStatus("未通过");
                        default:
                            break;
                    }
                }
            }

            SXSSFWorkbook workbook = itineraryBizService.exportExcel(memberInfos, competitionBusiness);
            String allPath = excelExportService.getExcelPath(fileName, "gatherInfo", new ExportExcel(), workbook);
            return AjaxResult.success((Object) allPath);
        } catch (Exception e) {
            logger.error("人员信息收集导出异常", e);
        }
        return AjaxResult.error("导出异常");
    }

    /**
     * 编辑人员信息
     *
     * @param id
     * @return
     */
    @DataControl
    @RequestMapping("toForm")
    public ModelAndView toForm(String id, @ControlParam(table = "gather_info_project", column = "create_by") String projectId, String groupId) {
        ModelAndView mv = new ModelAndView("gatherInfo/memberInfoForm");
        try {
            if (StringUtils.isEmpty(id)) {
                return new ModelAndView(Constant.ERROR_402);
            }
            if (StringUtils.isNotEmpty(id)) {
                /** 行程信息 **/
                GatherInfoMember memberInfo = gatherInfoMemberService.get(id);
                if (null == memberInfo) {
                    return new ModelAndView(Constant.ERROR_402);
                }
                List<GatherInfoItinerary> goItineraries = gatherInfoItineraryService.list(new GatherInfoItinerary(id, "go"));
                if (goItineraries.size() == 0) {
                    goItineraries.add(new GatherInfoItinerary());
                } else {
                    mv.addObject("goFirst", goItineraries.get(0));
                }
                List<GatherInfoItinerary> backItineraries = gatherInfoItineraryService.list(new GatherInfoItinerary(id, "back"));
                if (backItineraries.size() == 0) {
                    backItineraries.add(new GatherInfoItinerary());
                } else {
                    mv.addObject("backFirst", backItineraries.get(0));
                }
                memberInfo.setGoItineraries(goItineraries);
                memberInfo.setBackItineraries(backItineraries);
                mv.addObject("memberInfo", memberInfo);
                /** 基本信息 **/
                Member member = memberService.get(memberInfo.getMemberId());
                mv.addObject("member", member);
                /** 保险信息 **/
                MemberInfo mInfo = memberInfoService.findByMemberId(member.getId());
                mv.addObject("mInfo", mInfo);

                if (StringUtils.isNotEmpty(member.getIndustry())) {
                    Industry industry = industryService.get(member.getIndustry());
                    mv.addObject("inParent", industry.getParentId());
                }

                if (StringUtils.isNotEmpty(member.getCity())) {
                    Area area = areaService.get(member.getCity());
                    mv.addObject("arParent", area.getParentId());
                }
            }

            Area area = new Area();
            area.setParentId("1");
            List<Area> areas = areaService.list(area);
            mv.addObject("areas", areas);

            Industry industry = new Industry();
            industry.setParentId("0");
            List<Industry> industries = industryService.list(industry);
            mv.addObject("industries", industries);

            if (StringUtils.isNotEmpty(groupId)) {
                GatherInfoGroup gatherInfoGroup = gatherInfoGroupService.get(groupId);
                mv.addObject("group", gatherInfoGroup);
            }

            if (StringUtils.isNotEmpty(projectId)) {
                GatherInfoProject gatherInfoProject = gatherInfoProjectService.get(projectId);
                mv.addObject("project", gatherInfoProject);
            }
        } catch (Exception e) {
            logger.error("异常", e);
        }
        return mv;
    }

    /**
     * 新增人员
     *
     * @param projectId
     * @return
     */
    @DataControl
    @RequestMapping(value = "addMember")
    public ModelAndView addMember(@ControlParam(table = "gather_info_project", column = "create_by") String projectId, String groupId) {
        ModelAndView mv = new ModelAndView("gatherInfo/addMember");

        if (StringUtils.isNotEmpty(groupId)) {
            GatherInfoGroup gatherInfoGroup = gatherInfoGroupService.get(groupId);
            mv.addObject("group", gatherInfoGroup);

            projectId = gatherInfoGroup.getProjectId();
        }

        if (StringUtils.isNotEmpty(projectId)) {
            GatherInfoProject gatherInfoProject = gatherInfoProjectService.get(projectId);
            mv.addObject("project", gatherInfoProject);
        }

        Industry industry = new Industry();
        industry.setParentId("0");
        List<Industry> industries = industryService.list(industry);
        mv.addObject("industries", industries);

        Area area = new Area();
        area.setParentId("1");
        List<Area> areas = areaService.list(area);
        mv.addObject("areas", areas);
        return mv;
    }

    /**
     * 查看基本信息
     *
     * @param gMemberId
     * @return
     */
    @RequestMapping("getBaseInfo")
    public ModelAndView getBaseInfo(String gMemberId) {
        ModelAndView mv = new ModelAndView("gatherInfo/baseInfo");

        GatherInfoMember infoMember = gatherInfoMemberService.get(gMemberId);
        mv.addObject("infoMember", infoMember);
        Member member = memberService.get(infoMember.getMemberId());
        mv.addObject("member", member);
        MemberInfo memberInfo = memberInfoService.findByMemberId(member.getId());
        if (memberInfo == null) {
            memberInfo = new MemberInfo();
        }
        mv.addObject("memberInfo", memberInfo);

        // 设置城市名字
        if (!Strings.isNullOrEmpty(member.getCity())) {
            Area area = areaService.get(member.getCity());
            if (null != area) {
                mv.addObject("cityName", area.getName());
            }
        }
        // 设置行业名字
        if (!Strings.isNullOrEmpty(member.getIndustry())) {
            Industry industry = industryService.get(member.getIndustry());
            if (null != industry) {
                mv.addObject("industryName", industry.getName());
            }
        }
        return mv;
    }

    /**
     * 基本信息审核
     *
     * @param id
     * @param perfectState
     * @return
     */
    @ResponseBody
    @RequestMapping("verifyBaseInfo")
    public AjaxResult verifyBaseInfo(String id, String perfectState, String infoMemberId) {
        if (StringUtils.isNotEmpty(id)) {
            Member member = memberService.get(id);
            member.setPerfectState(perfectState);
            memberService.update(member);

            GatherInfoMember infoMember = gatherInfoMemberService.get(infoMemberId);
            infoMember.setBaseStatus(perfectState);
            gatherInfoMemberService.update(infoMember);
        }
        return AjaxResult.success();
    }

    /**
     * 保险信息审核
     *
     * @param id
     * @param perfectState
     * @return
     */
    @ResponseBody
    @RequestMapping("verifyInsuranceInfo")
    public AjaxResult verifyInsuranceInfo(String id, String perfectState, String infoMemberId) {
        if (StringUtils.isNotEmpty(id)) {
            MemberInfo memberInfo = memberInfoService.get(id);
            memberInfo.setPerfectState(perfectState);
            memberInfoService.update(memberInfo);

            GatherInfoMember infoMember = gatherInfoMemberService.get(infoMemberId);
            infoMember.setInsuranceStatus(perfectState);
            gatherInfoMemberService.update(infoMember);
        }
        return AjaxResult.success();
    }

    @ResponseBody
    @RequestMapping("verifyItineraryInfo")
    public AjaxResult verifyItineraryInfo(String id, String perfectState) {
        if (StringUtils.isNotEmpty(id)) {
            GatherInfoMember memberInfo = gatherInfoMemberService.get(id);
            memberInfo.setItineraryStatus(perfectState);
            gatherInfoMemberService.update(memberInfo);
        }
        return AjaxResult.success();
    }

    /**
     * 查看保险信息
     *
     * @param memberId
     * @return
     */
    @RequestMapping("getInsuranceInfo")
    public ModelAndView getInsuranceInfo(String memberId, String infoMemberId) {
        ModelAndView mv = new ModelAndView("gatherInfo/insuranceInfo");
        Member member = memberService.get(memberId);
        mv.addObject("member", member);
        MemberInfo memberInfo = memberInfoService.findByMemberId(memberId);
        mv.addObject("memberInfo", memberInfo);

        GatherInfoMember infoMember = gatherInfoMemberService.get(infoMemberId);
        mv.addObject("infoMember", infoMember);
        return mv;
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @RequestMapping("getItineraryInfo")
    public ModelAndView getItineraryInfo(String id) {
        ModelAndView mv = new ModelAndView("gatherInfo/itineraryInfo");
        GatherInfoMember memberInfo = gatherInfoMemberService.get(id);
        List<GatherInfoItinerary> gos = gatherInfoItineraryService.list(new GatherInfoItinerary(memberInfo.getId(), "go"));
        if (gos.size() > 0) {
            mv.addObject("goFirst", gos.get(0));
        }
        List<GatherInfoItinerary> backs = gatherInfoItineraryService.list(new GatherInfoItinerary(memberInfo.getId(), "back"));
        if (backs.size() > 0) {
            mv.addObject("backFirst", backs.get(0));
        }
        memberInfo.setGoItineraries(gos);
        memberInfo.setBackItineraries(backs);
        mv.addObject("memberInfo", memberInfo);
        Member member = memberService.get(memberInfo.getMemberId());
        mv.addObject("member", member);
        return mv;
    }

    /**
     * 保存人员
     *
     * @param result
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "saveMember", method = RequestMethod.POST)
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult saveMember(String projectId, String memberId, String groupId, Member member, BindingResult result) {
        // 数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            String description = allErrors.get(0).getDefaultMessage();
            return AjaxResult.error(description);
        }

        try {
            GatherInfoMember infoMemberDB = gatherInfoMemberService.findByProjectAndMember(memberId, projectId);
            if (infoMemberDB != null && StringUtils.isNotEmpty(groupId)) {
                infoMemberDB.setGroupId(groupId);
            }
            if (infoMemberDB == null) {
                infoMemberDB = new GatherInfoMember();

                String currentUserId = RealmUtils.getCurrentUser().getId();
                infoMemberDB.setProjectId(projectId);
                infoMemberDB.setGroupId(groupId);
                infoMemberDB.setCreateBy(currentUserId);
                infoMemberDB.setUpdateBy(currentUserId);

                if (StringUtils.isEmpty(memberId)) {
                    Member mm = memberBizService.saveBiz(member, Member.MEMBER_PERSONAL);
                    memberId = mm.getId();
                }
                infoMemberDB.setMemberId(memberId);
                infoMemberDB.setDelFlag(BaseModel.DEL_FLAG_NORMAL);

                if (StringUtils.isNotEmpty(memberId)) {
                    Member memberDB = memberService.get(memberId);
                    infoMemberDB.setBaseStatus(memberDB.getPerfectState());

                    MemberInfo memberInfo = memberInfoService.findByMemberId(memberId);
                    if (memberInfo != null) {
                        infoMemberDB.setInsuranceStatus(memberInfo.getPerfectState());
                    }
                }

                gatherInfoMemberService.insert(infoMemberDB);

                // 机构成员所属
                PartnerMember partnerMember = new PartnerMember();
                String partnerId = gatherInfoProjectService.get(infoMemberDB.getProjectId()).getCreateBy();
                partnerMember.setPartnerId(partnerId);
                partnerMember.setMemberId(memberId);
                partnerMemberService.getSet(partnerMember);

                // 个人统计表添加数据
                memberPersonalCountBizService.getSet(partnerId, memberId);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("添加人员异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("添加人员失败");
        }
    }

    /**
     * 保存基本信息
     *
     * @param member
     * @param gMemberId
     * @param groupJobTitle
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "saveBaseInfo", method = RequestMethod.POST)
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult saveBaseInfo(Member member, MemberInfo memberInfo, String gMemberId, String groupJobTitle) {
        try {
            if (StringUtils.isNotEmpty(member.getId())) {
                Member dbMember = memberService.get(member.getId());
                MyBeanUtils.copyBeanNotNull2Bean(member, dbMember);
                if (StringUtils.isEmpty(dbMember.getPerfectState())) {
                    dbMember.setPerfectState(GatherInfoMemberStatus.NOT_AUDIT_STATUS.getCode());
                }
                memberService.update(dbMember);
            }

            gatherInfoMembersBizService.updateMemberInfoHealth(memberInfo, member.getId());

            if (StringUtils.isNotEmpty(gMemberId)) {
                GatherInfoMember dbGMember = gatherInfoMemberService.get(gMemberId);
                dbGMember.setGroupJobTitle(groupJobTitle);
                gatherInfoMemberService.update(dbGMember);
            }

            // 机构成员所属
            PartnerMember partnerMember = new PartnerMember();
            String partnerId = gatherInfoProjectService.get(gatherInfoMemberService.get(gMemberId).getProjectId()).getCreateBy();
            partnerMember.setPartnerId(partnerId);
            partnerMember.setMemberId(member.getId());
            partnerMemberService.getSet(partnerMember);

            // 个人统计表添加数据
            memberPersonalCountBizService.getSet(partnerId, member.getId());

            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("保存基本信息异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("保存基本信息异常");
        }
    }

    /**
     * 保存保险信息
     *
     * @param memberInfo
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "saveInsuranceInfo", method = RequestMethod.POST)
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult saveInsuranceInfo(MemberInfo memberInfo) {
        try {
            if (StringUtils.isEmpty(memberInfo.getPerfectState())) {
                memberInfo.setPerfectState(GatherInfoMemberStatus.NOT_AUDIT_STATUS.getCode());
            }
            if (StringUtils.isNotEmpty(memberInfo.getId())) {
                Member memberc = memberService.get(memberInfo.getMemberId());

                // 2018/5/14 加验证开关，如果关，验证通过，状态为未验证
                SysConfig sysConfig = sysConfigService.findByCode(ID_CARD_VERIFY_SWITCH);
                if (Boolean.TRUE.toString().equals(sysConfig.getValue())) {
                    if (memberInfo.getUseCertificate() == 0 && memberc.getIsCertified() == 0) {
                        //进行身份证和姓名验证
                        //得到该会员的信息
                        IdcardVerifyRequest idcardVerifyRequest = new IdcardVerifyRequest();
                        idcardVerifyRequest.setIdcard(memberInfo.getIdCard());
                        idcardVerifyRequest.setName(memberc.getFullname());
                        idcardVerifyRequest.setAppid(appid);
                        idcardVerifyRequest.setAppSecret(appSecret);
                        IdcardVerifyResult result = iIdcardVerifyService.verify(idcardVerifyRequest);

                        if (!result.getCode().equals(0)) {
                            return AjaxResult.error("身份证与姓名不匹配");
                        } else {
                            //存为已验证,改性别
                            memberc.setIsCertified(1);
                            if (result.getSex().equals("M")) {
                                memberc.setSex(1);
                            } else {
                                memberc.setSex(0);
                            }
                            memberService.update(memberc);
                        }
                    }
                }
                memberInfoService.update(memberInfo);
            } else {
                memberInfoService.insert(memberInfo);
            }
            // 机构成员所属
            PartnerMember partnerMember = new PartnerMember();
            MemberGroup member = RealmUtils.getCurrentUser();
            partnerMember.setPartnerId(member.getId());
            partnerMember.setMemberId(memberInfo.getMemberId());
            partnerMemberService.getSet(partnerMember);

            // 个人统计表添加数据
            memberPersonalCountBizService.getSet(member.getId(), memberInfo.getMemberId());

            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("保存保险信息异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("保存保险信息异常");
        }
    }

    /**
     * 保存人员信息
     *
     * @param memberInfo
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "saveItineraryInfo", method = RequestMethod.POST)
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult saveItineraryInfo(GatherInfoMember memberInfo) {
        try {
            gatherInfoMembersBizService.parseRoomTime(memberInfo);
            // 去程
            gatherInfoMembersBizService.parseItineraryTime2(memberInfo.getGoItineraries());
            // 返程
            gatherInfoMembersBizService.parseItineraryTime2(memberInfo.getBackItineraries());

            if (StringUtils.isEmpty(memberInfo.getId())) {
                memberInfo.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
                String memberId = RealmUtils.getCurrentUser().getId();
                memberInfo.setCreateBy(memberId);
                memberInfo.setUpdateBy(memberId);
                memberInfo.setItineraryStatus(GatherInfoMemberStatus.NOT_AUDIT_STATUS.getCode());
                String infoMemberId = gatherInfoMemberService.insert(memberInfo);

                gatherInfoMembersBizService.saveOrUpdate(memberInfo.getGoItineraries(), "go", infoMemberId, null);
                gatherInfoMembersBizService.saveOrUpdate(memberInfo.getBackItineraries(), "back", infoMemberId, null);
            } else {
                GatherInfoMember t = gatherInfoMemberService.get(memberInfo.getId());
                MyBeanUtils.copyBeanNotNull2Bean(memberInfo, t);
                if (StringUtils.isEmpty(t.getItineraryStatus())) {
                    t.setItineraryStatus(GatherInfoMemberStatus.NOT_AUDIT_STATUS.getCode());
                }
                gatherInfoMemberService.update(t);

                List<GatherInfoItinerary> gos = gatherInfoItineraryService.list(new GatherInfoItinerary(memberInfo.getId(), "go"));

                gatherInfoMembersBizService.saveOrUpdate(memberInfo.getGoItineraries(), "go", memberInfo.getId(), gos);
                gatherInfoMembersBizService.saveOrUpdate(memberInfo.getBackItineraries(), "back", memberInfo.getId(), null);
            }

            // 机构成员所属
            PartnerMember partnerMember = new PartnerMember();
            GatherInfoMember gatherInfoMember = gatherInfoMemberService.get(memberInfo.getId());
            String partnerId = gatherInfoProjectService.get(gatherInfoMember.getProjectId()).getCreateBy();
            partnerMember.setPartnerId(partnerId);
            partnerMember.setMemberId(gatherInfoMember.getMemberId());
            partnerMemberService.getSet(partnerMember);

            // 个人统计表添加数据
            memberPersonalCountBizService.getSet(partnerId, gatherInfoMember.getMemberId());

            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("保存行程信息失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("保存行程信息失败");
        }
    }

    /**
     * 手动认证身份证和姓名是否相符
     *
     * @param memberInfo
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "certifiedIdCard")
    public AjaxResult saveItineraryInfo(MemberInfo memberInfo) throws Exception {

        try {
            //得到该会员的信息
            Member member = memberService.get(memberInfo.getMemberId());
            //得到该会员的副表信息
            MemberInfo memberInfot = memberInfoService.findByMemberId(memberInfo.getMemberId());
            IdcardVerifyRequest idcardVerifyRequest = new IdcardVerifyRequest();
            idcardVerifyRequest.setIdcard(memberInfot.getIdCard());
            idcardVerifyRequest.setName(member.getFullname());
            idcardVerifyRequest.setAppid(appid);
            idcardVerifyRequest.setAppSecret(appSecret);
            IdcardVerifyResult result = iIdcardVerifyService.verify(idcardVerifyRequest);
            if (!result.getCode().equals(0)) {
                return AjaxResult.error("身份证与姓名不匹配");
            } else {
                //存为已验证,改性别
                member.setIsCertified(1);
                if (result.getSex().equals("M")) {
                    member.setSex(1);
                } else {
                    member.setSex(0);
                }
                memberService.update(member);
                return AjaxResult.success("身份证与姓名匹配");
            }
        } catch (Exception e) {
            logger.error("身份认证失败", e);
            return AjaxResult.error(e.getMessage());
        }
    }


    /**
     * 删除用户信息
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public AjaxResult delete(String id) {
        if (StringUtils.isEmpty(id)) {
            return AjaxResult.error("ID不能为空");
        }
        gatherInfoMemberService.delete(id);
        return AjaxResult.success();
    }

    /**
     * 手动同步用户信息 暂时解决赛事那边基本信息显示问题
     *
     * @param id
     * @return
     * @throws Exception
     */
    /*@ResponseBody
    @RequestMapping(value = "syncMemberInfo", method = RequestMethod.POST)
	public AjaxResult syncMemberInfo(String id) throws Exception {
		if (StringUtils.isEmpty(id)) {
			return AjaxResult.error("信息收集id不能为空");
		}
		GatherInfoMember infoMember = gatherInfoMemberService.get(id);
		if (infoMember == null) {
			return AjaxResult.error("信息收集对象不存在");
		}
		if (StringUtils.isEmpty(infoMember.getMemberId())) {
			return AjaxResult.error("用户id不能为空");
		}
		Member member = gatherInfoMembersBizService.updateMemberBaseInfo(infoMember, infoMember.getMemberId());
		if (member == null) {
			return AjaxResult.error("用户不存在");
		}
		
		gatherInfoMembersBizService.updateMemberSatelliteInfo(infoMember, infoMember.getMemberId());
		return AjaxResult.success();
	}*/
}
